{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Using FunctionTransformer to select columns\n\n\nShows how to use a function transformer in a pipeline. If you know your\ndataset's first principle component is irrelevant for a classification task,\nyou can use the FunctionTransformer to select all but the first column of the\nPCA transformed data.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.decomposition import PCA\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import FunctionTransformer\n\n\ndef _generate_vector(shift=0.5, noise=15):\n    return np.arange(1000) + (np.random.rand(1000) - shift) * noise\n\n\ndef generate_dataset():\n    \"\"\"\n    This dataset is two lines with a slope ~ 1, where one has\n    a y offset of ~100\n    \"\"\"\n    return np.vstack((\n        np.vstack((\n            _generate_vector(),\n            _generate_vector() + 100,\n        )).T,\n        np.vstack((\n            _generate_vector(),\n            _generate_vector(),\n        )).T,\n    )), np.hstack((np.zeros(1000), np.ones(1000)))\n\n\ndef all_but_first_column(X):\n    return X[:, 1:]\n\n\ndef drop_first_component(X, y):\n    \"\"\"\n    Create a pipeline with PCA and the column selector and use it to\n    transform the dataset.\n    \"\"\"\n    pipeline = make_pipeline(\n        PCA(), FunctionTransformer(all_but_first_column),\n    )\n    X_train, X_test, y_train, y_test = train_test_split(X, y)\n    pipeline.fit(X_train, y_train)\n    return pipeline.transform(X_test), y_test\n\n\nif __name__ == '__main__':\n    X, y = generate_dataset()\n    lw = 0\n    plt.figure()\n    plt.scatter(X[:, 0], X[:, 1], c=y, lw=lw)\n    plt.figure()\n    X_transformed, y_transformed = drop_first_component(*generate_dataset())\n    plt.scatter(\n        X_transformed[:, 0],\n        np.zeros(len(X_transformed)),\n        c=y_transformed,\n        lw=lw,\n        s=60\n    )\n    plt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.9"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}